package com.pivotal.cloud.crypto.codec;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @className: com.pivotal.cloud.security.crypto.codec.Utf8
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-Utf8类，主要位于Security安全模块-Utf8编码模块
 * @content: Utf8-Utf8编码
 * @author: Powered by Marklin
 * @datetime: 2025-06-24 13:57
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public final class Utf8 {

	private static final Charset CHARSET;

	static {
		CHARSET = StandardCharsets.UTF_8;
	}

	private Utf8() {
	}

	/**
	 * 编码
	 * @param input 字符串
	 * @return 返回结果
	 */
	public static byte[] encode(CharSequence input) {
		try {
			ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(input));
			byte[] bytesCopy = new byte[bytes.limit()];
			System.arraycopy(bytes.array(), 0, bytesCopy, 0, bytes.limit());
			return bytesCopy;
		}
		catch (CharacterCodingException exception) {
			throw new IllegalArgumentException("Encoding failed", exception);
		}
	}

	/**
	 * 解码
	 * @param bytes 字节数组
	 * @return 返回结果
	 */
	public static String decode(byte[] bytes) {
		try {
			return CHARSET.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
		}
		catch (CharacterCodingException exception) {
			throw new IllegalArgumentException("Decoding failed", exception);
		}
	}

}
